import { defineStore } from 'pinia';
import { pageSizes } from '@/enums/baseConstant';
import { storeMessage } from '@/utils/message';
import { storePagination } from '@/store/useStorePagination';
import {
  fetchCreateCourse,
  fetchDeleteCourse,
  fetchGetCourseDetail,
  fetchGetCourseList,
  fetchGetCourseOptions,
  fetchGetCoursePermissions,
  fetchUpdateCourse,
  fetchUpdateCoursePermissions,
  fetchGetCoursePrerequisites,
  fetchUpdateCoursePrerequisites,
  CourseQueryParams
} from '@/api/kg/course';

/**
 * 课程信息 Store
 */
export const useCourseStore = defineStore('courseStore', {
  state() {
    return {
      // 课程信息列表
      datalist: [],
      // 课程选项列表（用于下拉选择）
      courseOptions: [],
      // 查询表单
      form: {
        // 课程名称
        name: undefined,
        // 课程编码
        code: undefined,
        // 课程描述
        description: undefined,
      },
      // 分页查询结果
      pagination: {
        currentPage: 1,
        pageSize: pageSizes[0],
        total: 0,
        pageSizes,
      },
      // 加载
      loading: false,
    };
  },
  getters: {},
  actions: {
    /** 获取课程列表（带分页和搜索） */
    async getCourseList() {
      this.loading = true;
      try {
        // 整理请求参数
        const params: CourseQueryParams = {
          ...this.form,
          currentPage: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        };

        // 过滤掉undefined的属性
        Object.keys(params).forEach(key => {
          if (params[key as keyof CourseQueryParams] === undefined) {
            delete params[key as keyof CourseQueryParams];
          }
        });

        const result = await fetchGetCourseList(params);
        if (result.code === 200) {
          this.datalist = result.data.list || [];
          this.pagination.total = result.data.total;
          this.pagination.currentPage = result.data.pageNo;
          this.pagination.pageSize = result.data.pageSize;
          return result.data.list;
        }
        return [];
      } finally {
        this.loading = false;
      }
    },

    /** 获取所有课程选项（用于下拉选择） */
    async getCourseOptions() {
      try {
        const result = await fetchGetCourseOptions();
        if (result.code === 200) {
          this.courseOptions = result.data || [];
          return result.data;
        }
        return [];
      } catch (error) {
        console.error('获取课程选项失败:', error);
        return [];
      }
    },

    /** 获取课程详情 */
    async getCourseDetail(id: string) {
      const result = await fetchGetCourseDetail(id);
      if (result.code !== 200) return null;
      return result.data;
    },

    /** 创建课程 */
    async createCourse(data: any) {
      const result = await fetchCreateCourse(data);
      return storeMessage(result);
    },

    /** 更新课程信息 */
    async updateCourse(id: string, data: any) {
      const result = await fetchUpdateCourse(id, data);
      return storeMessage(result);
    },

    /** 删除课程 */
    async deleteCourse(id: string) {
      const result = await fetchDeleteCourse(id);
      return storeMessage(result);
    },

    /** 获取课程授权用户列表 */
    async getCoursePermissions(courseId: string) {
      const result = await fetchGetCoursePermissions(courseId);
      if (result.code !== 200) return [];
      return result.data;
    },

    /** 更新课程授权用户列表 */
    async updateCoursePermissions(courseId: string, userIds: string[]) {
      const result = await fetchUpdateCoursePermissions(courseId, userIds);
      return storeMessage(result);
    },

    /** 获取课程的前置课程列表 */
    async getCoursePrerequisites(courseId: string) {
      const result = await fetchGetCoursePrerequisites(courseId);
      if (result.code !== 200) return [];
      return result.data;
    },

    /** 更新课程的前置课程列表 */
    async updateCoursePrerequisites(courseId: string, preCourseIds: string[]) {
      const result = await fetchUpdateCoursePrerequisites(courseId, preCourseIds);
      return storeMessage(result);
    },

    /** 重置表单 */
    resetForm() {
      this.form = {
        name: undefined,
        code: undefined,
        description: undefined
      };
      this.pagination.currentPage = 1;
      this.pagination.pageSize = pageSizes[0];
    },
  },
});
